import * as d3 from 'd3';
import { expose } from 'comlink';

// 定义数据类型
interface HerbNode {
  id: string;
  name: string;
  category: string;
  properties: {
    性: string;
    味: string[];
  };
  origin: [number, number];
  model: string;
}

interface RelationEdge {
  source: string;
  target: string;
  type: string;
  strength: number;
}

// 处理布局计算
async function processLayout(nodes: HerbNode[], edges: RelationEdge[]) {
  const simulation = d3.forceSimulation(nodes as any)
    .force('charge', d3.forceManyBody().strength(-30))
    .force('link', d3.forceLink(edges as any).id((d: any) => d.id).distance(50))
    .force('center', d3.forceCenter(0, 0))
    .stop();

  // 运行模拟直到收敛
  for (let i = 0; i < 300; i++) simulation.tick();

  return {
    nodes,
    edges
  };
}

// 处理数据分块
function chunkData<T>(data: T[], chunkSize: number): T[][] {
  const chunks: T[][] = [];
  for (let i = 0; i < data.length; i += chunkSize) {
    chunks.push(data.slice(i, i + chunkSize));
  }
  return chunks;
}

// 导出 worker 函数
const worker = {
  processLayout,
  chunkData
};

expose(worker); 